package com.net2s.servlets;

import java.io.IOException;
import java.util.Hashtable;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.net2s.bbdd.User;
import com.net2s.bbdd.UtilSQL;
import com.net2s.utils.Messages;

/**
 * Servlet implementation class ServletListUser
 */
public class ServletListUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	static Logger log= Logger.getLogger(ServletListUser.class);   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ServletListUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		procesaPeticion(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		procesaPeticion(request, response);
	}
	
	
	private void procesaPeticion (HttpServletRequest request, HttpServletResponse response){
		String sql="";
		request.getSession().setAttribute("mensajebaja", null);
		request.getSession().setAttribute("operacionAdmin", request.getParameter("operacion"));
		if(request.getParameter("id")!=null && !request.getParameter("id").equals("0"))
			request.getSession().setAttribute("id", request.getParameter("id"));
		if(request.getParameter("operacion").equals("baja")){
			sql="delete from users where id=" + request.getParameter("id");
			try{
				
				UtilSQL.executeQuery(sql);
			}catch(Exception e){
				log.error("Error " + e);
				request.getSession().setAttribute("mensajebaja", e.getMessage());
			}
			request.getSession().setAttribute("mensajebaja", Messages.getString("DeleteUser.OK"));
			try{
			response.sendRedirect(response.encodeRedirectURL("administracion.jsp"));
			}catch(Exception e){
				log.error(e);
			}
		}
		
		if(request.getParameter("operacion").equals("update")){
			String query = "update users set nombre='" + request.getParameter("nombre") +
					     "', apellidos='" + request.getParameter("apellidos") +
						 "',username='" + request.getParameter("user");
					    // "',password='" + request.getParameter("password");
					    
			if (request.getParameter("tipo")!=null){
				if (request.getParameter("tipo").equals("1"))
					query = query + "',profile='Consulta',Admin='N'";
				if (request.getParameter("tipo").equals("2"))
					query = query + "',profile='Marketing',Admin='N'";
				if (request.getParameter("tipo").equals("3"))
					query = query + "',profile='Marketing',admin='Y'";
			}
			query = query + " where id=" + request.getSession().getAttribute("id");
			try{
				log.info(query);
				UtilSQL.executeQuery(query);
				
			request.getSession().setAttribute("operacionAdmin", null);
			response.sendRedirect(response.encodeRedirectURL("administracion.jsp"));
			}catch(Exception e){
				log.error(e.getMessage());
			}
		}
		
		if(request.getParameter("operacion").equals("modificacion")){
			try{
				request.getSession().setAttribute("id", request.getParameter("id"));
				String query = "select username,profile,nombre,apellidos,admin from users where id=" + request.getParameter("id");
				try{
					String[] camposRecogida= {"username","profile","nombre","apellidos","admin"};
					Hashtable[] result = UtilSQL.getQuery(query, camposRecogida);
					User usuario = new User((String)result[0].get("username"),"",(String)result[0].get("profile"),
											(String)result[0].get("nombre"),(String)result[0].get("apellidos"),(String)result[0].get("admin"));
					request.getSession().setAttribute("usuario", usuario);
				}catch(Exception e){
					log.error("Excepcion " + e.getMessage());
				}
				response.sendRedirect(response.encodeRedirectURL("administracion.jsp"));
				}catch(Exception e){
					log.error(e);
				}
		}
		
		if(request.getParameter("operacion").equals("alta")){
			System.out.println(request.getParameter("tipo"));
			String queryPrevia = "select username from users where username='" + request.getParameter("user") + "'";
			
			String query = "Insert into users(username,profile,nombre,apellidos,admin) " + 
			" values('" + request.getParameter("user") + "','" ;
			if(request.getParameter("tipo").equals("1"))
				query=query + "Consulta','";
			else if (request.getParameter("tipo").equals("2") || request.getParameter("tipo").equals("3"))
				query = query + "Marketing','";


			query=query + request.getParameter("nombre") + "','" + request.getParameter("apellidos") + "','";

			if(request.getParameter("tipo").equals("3"))
				query = query + "Y')";
			if(!request.getParameter("tipo").equals("3"))
				query = query + "N')";

			log.info(query);
			Hashtable[] listado=null;
			try{
				String[] camposRecogida = {"username"};
				listado = UtilSQL.getQuery(queryPrevia,camposRecogida);
			}catch(Exception e){
				log.error(e.getMessage());
				
			}
			try{
				if(listado==null)
					UtilSQL.executeQuery(query);
				request.getSession().setAttribute("createUser","Usuario Creado Correctamente");


			}catch(Exception e){
				request.getSession().setAttribute("createUser", "Error al crear Usuario");
				log.error(e.getMessage());

			}
			try{
				response.sendRedirect(response.encodeRedirectURL("administracion.jsp"));
			}catch(Exception e){
				log.error("Error " + e);
			}
			//}
		}


	}
}
